package com.ruoyi.common.utils.ocr;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.io.file.FileNameUtil;
import com.ruoyi.common.config.RuoYiConfig;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

public class PDFUtils {
    public static File pdf2Jpg(File pdfFile) {
        // 加载PDF文档
        try (PDDocument document = PDDocument.load(pdfFile)) {
            // 创建PDF渲染器
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            // 获取第一页的图像（图像格式为RGB）
            BufferedImage image = pdfRenderer.renderImageWithDPI(0, 300, ImageType.RGB);
            String savePath = RuoYiConfig.getUploadPath()+new DateTime().toString("yyyy/MM/dd");
            String newFilename = FileNameUtil.getPrefix(pdfFile) + "_" + System.currentTimeMillis() + ".jpg";
            // 将图像写入文件
            File file = new File(savePath + "/" + newFilename);
            ImageIO.write(image, "JPEG", file);
            return file;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 使用pdfbox将整个pdf转换成图片
     *
     * @param fileAddress 文件地址 如:C:\\Users\\user\\Desktop\\test
     * @param filename    PDF文件名不带后缀名
     * @param type        图片类型 png 和 jpg
     */
    public static void pdf2png(String fileAddress, String filename, String type) {
        long startTime = System.currentTimeMillis();
        // 将文件地址和文件名拼接成路径 注意：线上环境不能使用\\拼接
        File file = new File(fileAddress + "\\" + filename + ".pdf");
        try {
            // 写入文件
            PDDocument doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                // dpi为144，越高越清晰，转换越慢
                BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
                // 将图片写出到该路径下
                ImageIO.write(image, type, new File(fileAddress + "\\" + filename + "_" + (i + 1) + "." + type));
            }
            long endTime = System.currentTimeMillis();
            System.out.println("共耗时：" + ((endTime - startTime) / 1000.0) + "秒");  //转化用时
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
